package com.loveyukari.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.loveyukari.dao.XmMessageDao;
import com.loveyukari.model.XmMessage;

/**
*
*yangshaohua
*2017年2月1日下午4:47:16
**/

@Repository
public class JdbcXmMessageDao extends BaseDao implements XmMessageDao{

	public void insertXmMessage(XmMessage xmMessage) {
		String sql = "insert into xm_message (message,name,create_time) values (?,?,?)";
		this.getJdbcTemplate().update(sql,xmMessage.getMessage(),xmMessage.getName(),xmMessage.getCreateTime());
		
	}

	public List<XmMessage> selectXmMessageBySize(Integer size) {
		String sql = "select * from xm_message order by id desc";
		if (size != null){
			sql += " limit "+ size;
		}
		List<XmMessage> list = this.getJdbcTemplate().query(sql, new XmMessageRowMapper());
		return list;
	}
	
	public XmMessage selectXmMessageByLast(String name){
		List<XmMessage> list = new ArrayList<XmMessage>();
		if (StringUtils.isEmpty(name)){
			String sql = "select * from xm_message order by id desc limit 1";
			list = this.getJdbcTemplate().query(sql, new XmMessageRowMapper());
		} else {
			String sql = "select * from xm_message where name = ? order by id desc limit 1";
			list = this.getJdbcTemplate().query(sql, new XmMessageRowMapper(),name);
		}
		if (list.isEmpty()){
			return null;
		} else {
			return list.get(0);
		}
	}
	
	private class XmMessageRowMapper implements RowMapper<XmMessage>{

		public XmMessage mapRow(ResultSet rs, int rowNum) throws SQLException {
			XmMessage xmMessage = new XmMessage();
			xmMessage.setId(rs.getInt("id"));
			xmMessage.setName(rs.getString("name"));
			xmMessage.setCreateTime(rs.getTimestamp("create_time"));
			xmMessage.setMessage(rs.getString("message"));
			return xmMessage;
		}
		
	}

}
